import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author GAX
 * @date 2025-09-09
 */

public class CASDemo {
    private AtomicInteger atomicInteger = new AtomicInteger(0);

    public AtomicInteger getNumber() {
        return atomicInteger;
    }

    // 由于采用了原子整型类，完全不用加锁
    public void setAtomicInteger() {
        atomicInteger.incrementAndGet();
    }

    public static void main(String[] args) throws InterruptedException {
        CASDemo casDemo = new CASDemo();
        // 100 个线程，计数器初始值为 100
        CountDownLatch countDownLatch = new CountDownLatch(100);

        for (int i = 1; i <= 100; i++) {
            new Thread(()->{
                // 每个线程加到 100
                for (int j = 1; j <= 100; j++) {
                    casDemo.setAtomicInteger();
                }
                // 每个线程执行完，都让计数器减 1
                countDownLatch.countDown();
            }, String.valueOf(i)).start();
        }
        // 让 main 线程在这里等待，直到 100 个线程都执行完毕内部的加法操作
        countDownLatch.await();
        System.out.println(Thread.currentThread().getName() + "\t" + "获得最后的结果：" + casDemo.getNumber());
    }
}